package es.mgil.energyToggle;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioManager;
import android.preference.PreferenceManager;
import android.provider.Settings.SettingNotFoundException;
import android.provider.Settings.System;
import android.widget.RemoteViews;

/**
 * al iniciar: on update
 * 
 * al afegir-lo: on enabled, on update
 * 
 * al tocar-lo: on reveive
 * 
 * al eliminar-lo: on deleted, on disabled
 * 
 * al apagar: res
 * 
 * @author marc
 */
public class EnergyToggleWidgetProvider extends AppWidgetProvider {
	public static final String CLICK = "es.mgil.energyToggle.WidgetApp.CLICK";

	public static final int NO_STATE = -1;
	public static final int MIN_STATE = 0;
	public static final int NORMAL_STATE = 1;
	// public static int STATE = NO_STATE;

	public static boolean changing_brightness = false;

	private final String state_ID = "energyToggleState";

	private final String normal_volume_music_ID = "normal_volume_music";
	private final String normal_volume_ring_ID = "normal_volume_ring";
	private final String normal_volume_notifications_ID = "normal_volume_notifications";
	private final String normal_volume_system_ID = "normal_volume_system";
	private final String normal_vibration_notifications_ID = "normal_vibration_notifications";
	private final String normal_vibration_ring_ID = "normal_vibration_ring";
	public static final String normal_brightness_ID = "normal_brightness";

	private final int min_volume_music = 4;
	private final int min_volume_ring = 1;
	private final int min_volume_notifications = 1;
	private final int min_volume_system = 1;
	private final int min_vibration_notifications = AudioManager.VIBRATE_SETTING_OFF;
	private final int min_vibration_ring = AudioManager.VIBRATE_SETTING_OFF;
	public static final int min_brightness = 1;

	private final int defValue = -1;

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		if (prefs.getInt(state_ID, defValue) == defValue) {
			Editor editor = prefs.edit();
			editor.putInt(state_ID, NO_STATE);
			editor.commit();
		}

		storeNormalState(context);
		setNormalState(context);
		updateLayout(context);
	}

	@Override
	public void onEnabled(Context context) {
	}

	@Override
	public void onDisabled(Context context) {
		setNormalState(context);
		removePreferences(context);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
		} else if (intent.getAction().equals(CLICK)) {
			switchState(context);
			updateLayout(context);
		} else {
			super.onReceive(context, intent);
		}
	}

	private void updateLayout(Context context) {
		RemoteViews views = new RemoteViews(context.getPackageName(),
				R.layout.widget);

		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		int state = prefs.getInt(state_ID, defValue);

		views.setImageViewResource(R.id.Image,
				state == NORMAL_STATE ? R.drawable.icon_normal
						: state == MIN_STATE ? R.drawable.icon_min
								: R.drawable.icon);

		// assign Click
		Intent click_intent = new Intent(CLICK);
		PendingIntent pending_intent = PendingIntent.getBroadcast(context, 0,
				click_intent, 0);
		views.setOnClickPendingIntent(R.id.widgetLayout, pending_intent);

		// update the widget
		AppWidgetManager manager = AppWidgetManager.getInstance(context);
		ComponentName widget = new ComponentName(context,
				EnergyToggleWidgetProvider.class);
		manager.updateAppWidget(widget, views);
	}

	private void switchState(Context context) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		int state = prefs.getInt(state_ID, defValue);

		if (state == NORMAL_STATE) {
			setMinState(context);
		} else if (state == MIN_STATE) {
			setNormalState(context);
		} else {
			setNormalState(context);
		}
	}

	private void storeNormalState(Context context) {
		// Get the AudioManager
		AudioManager audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);

		// Get Shared preferences and its editor
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		Editor editor = prefs.edit();

		if (prefs.getInt(normal_volume_music_ID, defValue) == defValue) {
			editor.putInt(normal_volume_music_ID,
					audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
		}

		if (prefs.getInt(normal_volume_ring_ID, defValue) == defValue) {
			editor.putInt(normal_volume_ring_ID,
					audioManager.getStreamVolume(AudioManager.STREAM_RING));
		}

		if (prefs.getInt(normal_volume_notifications_ID, defValue) == defValue) {
			editor.putInt(normal_volume_notifications_ID, audioManager
					.getStreamVolume(AudioManager.STREAM_NOTIFICATION));
		}

		if (prefs.getInt(normal_volume_system_ID, defValue) == defValue) {
			editor.putInt(normal_volume_system_ID,
					audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM));
		}

		if (prefs.getInt(normal_vibration_ring_ID, defValue) == defValue) {
			editor.putInt(normal_vibration_ring_ID, audioManager
					.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER));
		}

		if (prefs.getInt(normal_vibration_notifications_ID, defValue) == defValue) {
			editor.putInt(normal_vibration_notifications_ID, audioManager
					.getVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION));
		}

		if (prefs.getInt(normal_brightness_ID, defValue) == defValue) {
			try {
				editor.putInt(normal_brightness_ID, System.getInt(
						context.getContentResolver(), System.SCREEN_BRIGHTNESS));
			} catch (SettingNotFoundException e) {
			}
		}

		editor.commit();
	}

	private void removePreferences(Context context) {
		// Get Shared preferences and its editor
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		Editor editor = prefs.edit();

		editor.remove(state_ID);
		editor.remove(normal_volume_music_ID);
		editor.remove(normal_volume_ring_ID);
		editor.remove(normal_volume_notifications_ID);
		editor.remove(normal_volume_system_ID);
		editor.remove(normal_vibration_ring_ID);
		editor.remove(normal_vibration_notifications_ID);
		editor.remove(normal_brightness_ID);

		editor.commit();
	}

	private void setNormalState(Context context) {
		// Get the AudioManager
		AudioManager audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);

		// Get shared Preferencess
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);

		audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
				prefs.getInt(normal_volume_music_ID, 1), 0);
		audioManager.setStreamVolume(AudioManager.STREAM_RING,
				prefs.getInt(normal_volume_ring_ID, 1), 0);
		audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION,
				prefs.getInt(normal_volume_notifications_ID, 1), 0);
		audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM,
				prefs.getInt(normal_volume_system_ID, 1), 0);
		audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,
				prefs.getInt(normal_vibration_ring_ID, 0));
		audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION,
				prefs.getInt(normal_vibration_notifications_ID, 0));
		System.putInt(context.getContentResolver(), System.SCREEN_BRIGHTNESS,
				prefs.getInt(normal_brightness_ID, 0));
		// launchActivityForBrightness(context);

		Editor editor = prefs.edit();
		editor.putInt(state_ID, NORMAL_STATE);
		editor.commit();
	}

	private void setMinState(Context context) {
		// Get the AudioManager
		AudioManager audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);

		// set the min values
		audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
				min_volume_music, 0);
		audioManager.setStreamVolume(AudioManager.STREAM_RING, min_volume_ring,
				0);
		audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION,
				min_volume_notifications, 0);
		audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM,
				min_volume_system, 0);
		audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,
				min_vibration_ring);
		audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION,
				min_vibration_notifications);
		System.putInt(context.getContentResolver(), System.SCREEN_BRIGHTNESS,
				min_brightness);
		// launchActivityForBrightness(context);

		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		Editor editor = prefs.edit();
		editor.putInt(state_ID, MIN_STATE);
		editor.commit();
	}

	// private void launchActivityForBrightness(Context context) {
	// try {
	// changing_brightness = true;
	// Intent intent = new Intent(context, EnergyToggle.class);
	// PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
	// intent, 0);
	// RemoteViews updateViews = new RemoteViews(context.getPackageName(),
	// R.layout.widget);
	// updateViews.setOnClickPendingIntent(0, pendingIntent);
	// AppWidgetManager mgr = AppWidgetManager.getInstance(context);
	// ComponentName comp = new ComponentName(context.getPackageName(),
	// EnergyToggleWidgetProvider.class.getName());
	// mgr.updateAppWidget(comp, updateViews);
	// } catch (Exception e) {
	// e.toString();
	// }
	// }
}